var Wo = function() {
	//用户名正则，4到16位（字母，数字，下划线，减号）
	var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
	//密码强度正则，最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符
	var pPattern = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/;
	//Email正则
	var ePattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,5})$/;
	//手机号正则
	var mPattern = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;
	//包含中文正则
	var cnPattern = /[\u4E00-\u9FA5]/;
	//注册
	var register = function() {
		$("input[name=submitBtn]").click(function() {
			var agreement = $("#agreement").prop("checked"),
				WoUser = $("#WoUser").val(),
				WoPass = $("#WoPass").val(),
				WoPass2 = $("#WoPass2").val(),
				WoMail = $("#WoMail").val(),
				htm, msg;
			msg = "";
			$("#agreement").val(agreement);
			if(!uPattern.test(WoUser)) {
				msg = "用户名长度4-16位";
				Wo.log_error(msg)
				return false;
			}
			if(WoPass.length < 6) {
				msg = "密码最少6位"
				Wo.log_error(msg)
				return false;
			}
			if(WoPass != WoPass2) {
				msg = "两次密码不一致"
				Wo.log_error(msg)
				return false;
			}
			if(!ePattern.test(WoMail)) {
				msg = "邮箱格式不正确"
				Wo.log_error(msg)
				return false;
			}
			if($("#agreement").val() != "true") {
				msg = "未阅读用户协议和隐私条款"
				Wo.log_error(msg)
				return false;
			}
			$('.error-msg').remove();
			//			$("#authForm").submit();
			agreement = $("#agreement").prop("checked"),
				WoUser = $("#WoUser").val(),
				WoPass = $("#WoPass").val(),
				WoPass2 = $("#WoPass2").val(),
				WoMail = $("#WoMail").val();
			$.ajax({
				type: "post",
				url: "/register/auth",
				dataType: 'json',
				data: {
					"agreement": agreement,
					"WoUser": WoUser,
					"WoPass": String(hex_md5(WoPass)),
					"WoPass2": String(hex_md5(WoPass)),
					"WoMail": WoMail
				},
				success: function(data) {
					console.log(data)
					if(data) {
						Wo.log_error(data.msg)
					} else {
						console.log("注册成功")
						window.location.href = "/";
					}
				},
				error: function(err) {
					console.error(err);
				}
			});
		})
	}

	//登录
	var LoginFun = function() {
		$("input[name=submitBtn]").click(function() {
			var agreement = $("#agreement").prop("checked"),
				WoUser = $("#WoUser").val(),
				WoPass = $("#WoPass").val(),
				msg;
			$("#agreement").val(agreement);
			if(!uPattern.test(WoUser)) {
				msg = "用户名长度4-16位";
				Wo.log_error(msg)
				return false;
			}
			if(WoPass.length < 6) {
				msg = "密码最少6位"
				Wo.log_error(msg)
				return false;
			}
			if($("#agreement").val() != "true") {
				msg = "未阅读用户协议和隐私条款"
				Wo.log_error(msg)
				return false;
			}
			$('.error-msg').remove();
			agreement = $("#agreement").prop("checked"),
				WoUser = $("#WoUser").val(),
				WoPass = $("#WoPass").val();
			$.ajax({
				type: "post",
				url: "/login/auth",
				dataType: 'json',
				data: {
					"agreement": agreement,
					"WoUser": WoUser,
					"WoPass": String(hex_md5(WoPass))
				},
				success: function(data) {
					if(data) {
						Wo.log_error(data.msg)
					} else {
						window.location.href = "/";
					}

				},
				error: function(err) {
					console.error(err);
				}
			});
		})
	}

	//获取首页内容
	var PubLish = function(url, obj) {
		$.ajax({
			url: url,
			type: 'post',
			data: {
				'User_id': obj
			},
			dataType: 'json',
			success: function(data) {
				console.log(data)
				if(data.msg == "success") {
					var htm = "";
					for(var i in data.info['sub'].Sub_id) {
						htm += '<li>' +
							'	<div class="detail-wrapper">' +
							'		<div class="header ">' +
							'			<a href="/user/' + data.info['user'].User_id[i] + '/">';
						if(data.info['user'].UserImg[i]) {
							htm += '<img class="user-img lazy-load left" src="' + data.info['user'].UserImg[i] + '" onerror="this.src=\'/uploads/Face/Official/20171102/d1d3efab-772b-43ff-894f-251109d09227.jpg\'">';
						} else {
							htm += '<img class="user-img lazy-load left" src="/uploads/Face/Official/20171102/d1d3efab-772b-43ff-894f-251109d09227.jpg" onerror="this.src=\'/uploads/Face/Official/20171102/d1d3efab-772b-43ff-894f-251109d09227.jpg\'">';
						}
						htm += '				<div class="name-time-wrapper left">' +
							'					<span class="name">' + data.info['user'].Name[i] + '</span>' +
							'					<span class="time timeago" title="' + data.info['sub'].SubTime[i] + '">' + data.info['sub'].SubTime[i] + '</span>' +
							'				</div>' +
							'			</a>' +
							'		</div>' +
							'		<div class="content-wrapper">' +
							'			<a target="_blank" class="image share_url" href="' + data.info['sub'].Sub_id[i] + '/' + data.info['sub'].Sub_id[i] + '.html" data-group-id="74253776779">' +
							'				<div class="upload-txt  no-mb">' +
							'					<h1 class="title">' +
							'						<p>' + data.info['sub'].Content[i] + '</p>' +
							'					</h1>' +
							'				</div>' +
							'			</a>' +
							'		</div>' +
							'		<div class="options" data-group-id="74253776779">' +
							'			<ul>' +
							'				<li class="digg-wrapper ">' +
							'					<span class="digg">' + data.info['sub'].UpNumber[i] + '</span>' +
							'				</li>' +
							'				<li class="bury-wrapper ">' +
							'					<span class="bury">' + data.info['sub'].BuryNumber[i] + '</span>' +
							'				</li>' +
							'				<li class="repin-wrapper ">' +
							'					<span class="repin">' + data.info['sub'].SubColle[i] + '</span>' +
							'				</li>' +
							//								'				<li class="share-wrapper right" data-group-id="74253776779" data-url="http://neihanshequ.com/p74253776779/" data-text="避孕套的定价是否过高？￼：又要超薄，又要牢固不破，又要润滑剂，又要杀精剂，又要颜色，又要螺纹，又要香味，又要表面的东西吃下去没有副作用。 就这样才卖两块钱，你还嫌贵？" data-pic="">' +
							//								'					<span class="share">' + data.Content[i] + '</span>' +
							//								'				</li>' +
							'				<li class="post-comment-btn right">' +
							'					<span class="comment J-comment-count">' + data.info['sub'].SubCent[i] + '</span>' +
							'				</li>' +
							'			</ul>' +
							'		</div>' +
							'	</div>' +
							'</li>';
					}
					$("#detail-list").html(htm);
				}
			},
			error: function(err) {
				console.error(err);
			}
		})
	}
	//发布段子
	var publish_fun = function() {
		var imgData = {};
		$("#postContent").keydown(function() {
			$(".words-remain>span").text(300 - $("#postContent").val().length);
			if(300 - $("#postContent").val().length == 0) {

			}
		})
		$("#submitBtn").click(function() {
			if(!$.trim($("#postContent").val())) {
				alert("请填写内容");
				return false;
			}
			if(0 > 300 - $("#postContent").val().length) {
				alert("内容长度过长");
				return false;
			}
			$.ajax({
				type: "post",
				url: "/api/index/publish_post",
				async: true,
				data: {
					"Content": $("#postContent").val(),
					"ContentType": $("[name=activity_id]").val(),
					"ContentAnnex": $("#imgurl").val()
				},
				success: function(data) {
					if(data.msg != "success") {
						alert(data.msg)
					} else {
						alert("提交成功");
						$("#postPopupWindow").hide();
					}
				},
				error: function(err) {
					alert("出错,请联系管理员");
				}
			});
		})
	}

	//Layui 上传图片 (input file，预读img，url,失败重新传)
	var uploadImage = function(name1, name2, name3, name4) {
		layui.use('upload', function() {
			var $ = layui.jquery,
				upload = layui.upload;

			//普通图片上传
			var uploadInst = upload.render({
				elem: name1,
				url: '/api/index/upload',
				accept: 'images', //允许上传的文件类型
				drag: true, //是否允许拖拽
				before: function(obj) {
					//预读本地文件示例，不支持ie8
					obj.preview(function(index, file, result) {
						$(name2).attr('src', result); //图片链接（base64）
					});
				},
				done: function(res) {
					//如果上传失败
					if(res.code > 0) {
						return layer.msg('上传失败');
					}
					$(name3).val(res.file);
					//上传成功
				},
				error: function() {
					//演示失败状态，并实现重传
					var demoText = $(name4);
					demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
					demoText.find('.demo-reload').on('click', function() {
						uploadInst.upload();
					});
				}
			});
		});
	}

	return {
		win: function() {
			$("#postPopup").click(function() {
				$("#postPopupWindow").show();
			})
		},
		reg: function() {
			register();
		},
		log_error: function(error) {
			if($('.error-msg').length > 0) {
				$('.error-msg').remove();
			}
			var htm = "<div class='error-msg'><i class='y-icon icon-errormessage'></i>" + error + "<i class='y-right y-icon icon-clearicon' onclick='$(\".error-msg\").remove();' ></i> </div>";
			$(".baseLogin").prepend(htm);
		},
		PlainText: function(ContentType, Status) {
			this.win();
			if(!ContentType) {
				ContentType = 0;
			}
			if(!Status) {
				Status = 2;
			}
			$.ajax({
				url: "/",
				type: "post",
				datatype: "json",
				data: {
					"ContentType": ContentType,
					"Status": Status
				},
				success: function(data) {
					if(data.msg == "success") {
						var htm = "";
						for(var i in data.Sub_id) {
							htm += '<li>' +
								'	<div class="detail-wrapper">' +
								'		<div class="header ">' +
								'			<a href="/user/' + data.User_id[i] + '/">';
							if(data.UserImg[i]) {
								htm += '<img class="user-img lazy-load left" src="' + data.UserImg[i] + '" onerror="this.src=\'/uploads/Face/Official/20171102/d1d3efab-772b-43ff-894f-251109d09227.jpg\'">';
							} else {
								htm += '<img class="user-img lazy-load left" src="/uploads/Face/Official/20171102/d1d3efab-772b-43ff-894f-251109d09227.jpg" onerror="this.src=\'/uploads/Face/Official/20171102/d1d3efab-772b-43ff-894f-251109d09227.jpg\'">';
							}
							htm += '				<div class="name-time-wrapper left">' +
								'					<span class="name">' + data.Name[i] + '</span>' +
								'					<span class="time timeago" title="' + data.SubTime[i] + '">' + data.SubTime[i] + '</span>' +
								'				</div>' +
								'			</a>' +
								'		</div>' +
								'		<div class="content-wrapper">' +
								'			<a target="_blank" class="image share_url" href="' + data.Sub_id[i] + '/' + data.Sub_id[i] + '.html" data-group-id="74253776779">' +
								'				<div class="upload-txt  no-mb">' +
								'					<h1 class="title">' +
								'						<p>' + data.Content[i] + '</p>' +
								'					</h1>' +
								'				</div>' +
								'			</a>' +
								'		</div>' +
								'		<div class="options" data-group-id="74253776779">' +
								'			<ul>' +
								'				<li class="digg-wrapper ">' +
								'					<span class="digg">' + data.UpNumber[i] + '</span>' +
								'				</li>' +
								'				<li class="bury-wrapper ">' +
								'					<span class="bury">' + data.BuryNumber[i] + '</span>' +
								'				</li>' +
								'				<li class="repin-wrapper ">' +
								'					<span class="repin">' + data.SubColle[i] + '</span>' +
								'				</li>' +
								//								'				<li class="share-wrapper right" data-group-id="74253776779" data-url="http://neihanshequ.com/p74253776779/" data-text="避孕套的定价是否过高？￼：又要超薄，又要牢固不破，又要润滑剂，又要杀精剂，又要颜色，又要螺纹，又要香味，又要表面的东西吃下去没有副作用。 就这样才卖两块钱，你还嫌贵？" data-pic="">' +
								//								'					<span class="share">' + data.Content[i] + '</span>' +
								//								'				</li>' +
								'				<li class="post-comment-btn right">' +
								'					<span class="comment J-comment-count">' + data.SubCent[i] + '</span>' +
								'				</li>' +
								'			</ul>' +
								'		</div>' +
								'	</div>' +
								'</li>';
						}
						$("#detail-list").html(htm);
					}
				},
				error: function(err) {

				}
			})

		},
		login: function() {
			LoginFun();
		},
		pulish: function(url, obj) {
			this.win();
			PubLish(url, obj);
		},
		publish_post: function() {
			publish_fun();
		},
		uploadImg: function() {
			uploadImage();
		},
		//上传图片验证
		fileChange: function(target) {
			target = $(target);
			//检测上传文件的类型 
			var imgName = target.val();
			var ext, idx;
			if(imgName == '') {
				alert("请选择需要上传的文件!");
				return false;
			} else {
				idx = imgName.lastIndexOf(".");
				if(idx != -1) {
					ext = imgName.substr(idx + 1).toUpperCase();
					ext = ext.toLowerCase();
					// alert("ext="+ext);
					if(ext != 'jpg' && ext != 'png' && ext != 'jpeg' && ext != 'gif') {
						alert("图片格式不对，格式只能为(.jpg || .png || .jpeg || .gif)");
						return false;
					}
				} else {
					alert("图片格式不对，格式只能为(.jpg || .png || .jpeg || .gif)");
					return false;
				}
			}
			//检测上传文件的大小        
			var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
			var fileSize = 0;
			if(isIE && !target[0].files[0]) {
				var filePath = target.val();
				var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
				var file = fileSystem.GetFile(filePath);
				fileSize = file.Size;
			} else {
				fileSize = target[0].files[0].size;
			}

			var size = fileSize / 1024 / 1024;

			if(size > 2) {
				alert("文件大小不能超过2MB");
				return false;
			} else {
				return true;
			}
		},
		uploadimgurl: function() {
			var imgData = {};
			var form = new FormData(document.getElementById("imgform"));
			$.ajax({
				url: "/api/index/upload",
				type: "post",
				data: form,
				cache: false,
				processData: false,
				contentType: false,
				success: function(data) {
					$("#imgcode").val(data.code);
					$("#imgurl").val(data.file);
					$("#imgmsg").val(data.msg);
				},
				error: function(e) {
					console.log(e)
				}
			});
		}
	}
}();